package name.fowler.refactoring.simplestore.web;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/report/*")
public class ReportController extends HttpServlet{
    @Inject
    private ReportHandler reportHandler;

    @PersistenceUnit
    private EntityManagerFactory entityManagerFactory;

    @Override
    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try{
            Map<String,String[]> params = httpServletRequest.getParameterMap();
            if (params.size() == 0) {
                reportHandler.chooseReport(entityManager, httpServletRequest, httpServletResponse);
            } else {
                reportHandler.buildReport(entityManager, httpServletRequest, httpServletResponse, params);
            }
        } finally {
            entityManager.close();
        }
    }
}
